<?php

namespace App\Services\spider;

class TypeValidator
{

    /**
     * @var ITypeParser[] $parsers
     */
    private array $parsers = [];


    /**
     * @param ITypeParser[] $parsers
     */
    public function __construct(array $parsers)
    {
        $this->parsers = $parsers;
    }


    public function parse(IUrParser $urlParser, string $url,string $taskNo): ParseResult
    {

        foreach ($this->parsers as $parser) {
            if ($parser->isTarget($url)) {
                return $parser->parse($urlParser, $url,$taskNo);
            }
        }
        return ParseResult::of(false);
    }

    public function parseHtml(string $url, string $htmlContent): ParseResult
    {
        foreach ($this->parsers as $parser) {
            if ($parser->isTarget($url)) {
                return $parser->parseHtml($url, $htmlContent);
            }
        }
        return ParseResult::of(false);
    }


    /**
     * @param $url
     * @return string|null 返回类型
     */
    public function isTarget($url): ?string
    {
        foreach ($this->parsers as $parser) {
            if ($parser->isTarget($url)) {
                return $parser->type;
            }
        }
        return null;
    }


}